
define(function(require,exports,module){
    var $ = require("$");
	var Area = new function(){
        var step,
            selValue,
            areaData,
            INSIDEID = 3421,
            OUTSIDEID = 3418;
        this.init = function(dataUrl) {
            $.ajax({
                type: "POST",
                dataType:"json",
                url:dataUrl,
                async:false,
                success: function(data){
                    areaData = data;
                }
            });
        }
		
		//获取省份列表
        this.getProvs = function( selprov ) {
            var provs = [],
                i = 0,
                aselprov = selprov ? selprov : 0;
            for(var p in areaData) {
                if( p=='l' || p=='id' ) continue;
                provs[i] = {'id':p, 'name':areaData[p].n, 'sel':(aselprov==p),'trueId':areaData[p].id };
                i++;
            }
            return provs;
        };

        //获取城市列表
        this.getCitys = function( prov, selcity ) {
            var citys = [],
                i = 0,
                aselcity = selcity ? selcity : 0;
            if( areaData[prov].l == 0) {
                return false;
            }
            for(c in areaData[prov]['c']) {
                if( c=='l' || c=='id' ) continue;
                citys[i] = {'id':c, 'name':areaData[prov]['c'][c].n, 'sel':(aselcity==c), 'trueId':areaData[prov]['c'][c].id };
                i++;
            }
            return citys;
        };

        //获取县区列表
        this.getTowns = function( city, seltown ) {
            var towns = [],
                i = 0,
                aseltown = seltown ? seltown : 0,
                prov = Math.floor( city / 1000000 ) * 1000000;
            if( !areaData[prov] || !areaData[prov]['c'][city].l ) {
                return false;
            }
            for( t in areaData[prov]['c'][city]['t'] ) {
                if( t=='l' || t=='id' ) continue;
                towns[i] = {'id':t, 'name':areaData[prov]['c'][city]['t'][t].n, 'sel':(aseltown==t), 'trueId':areaData[prov]['c'][city]['t'][t].id };
                i++;
            }
            return towns;
        };
		//获取镇列表
		this.getVells = function(town,selvell){
			var vells = [],
                i = 0,
                aselvell = selvell ? selvell : 0,
                city = Math.floor( town / 10000 ) * 10000,
                prov = Math.floor( city / 1000000 ) * 1000000;
			if( !areaData[prov] || !areaData[prov]['c'][city] || !areaData[prov]['c'][city]['t'][town].l ){
				return false;
			}
			for( var v in areaData[prov]['c'][city]['t'][town]['v']){
                if( v=='l' || v=='id' ) continue;
				vells[i] = {'id':v, 'name': areaData[prov]['c'][city]['t'][town]['v'][v].n, 'sel':[aselvell==v], 'trueId': areaData[prov]['c'][city]['t'][town]['v'][v].id};
				i++;
			}
			return vells;
		}
		
		/***************************
        参数说明
        var areaConfig = {
        'conId'    : select容器id,
        'step'      : 选择框级数(可选, 默认3),
        'name1'     : 第一级选择框名称(可选),
        'name2'     : 第二级选择框名称(可选),
        'name3'     : 第三级选择框名称(可选),
        'name4'     : 第四级选择框名称(可选),
        'selValue' : 默认选中的项目(可选)
        };
        ***************************/
        this.makeSelect = function( areaConfig ) {
            //设置默认参数
            var conId, name1, name2, name3, name4, selProv, selCity, selTown, selVell, p;
            if( !areaConfig['conId'] ) {
                alert('地区选择框容器id必须指定!');
                return ;
            }
            conId = areaConfig['conId'];
            step  = !areaConfig['step']  ? 5 : areaConfig['step'];
            name1 = !areaConfig['name1'] ? 'ya_prov' : areaConfig['name1'];
            name2 = !areaConfig['name2'] ? 'ya_city' : areaConfig['name2'];
            name3 = !areaConfig['name3'] ? 'ya_town' : areaConfig['name3'];
			name4 = !areaConfig['name4'] ? 'ya_vell' : areaConfig['name4'];
            selValue  = !areaConfig['selValue']  ? 0 : areaConfig['selValue'];

            //计算选中的值
            if( selValue!=0 ) {
                if( selValue % 1000000 == 0) {
                    selProv = selValue;
                    selCity = selTown = 0;
                } else if( selValue % 10000 == 0) {
                    selProv = Math.floor( selValue / 1000000) * 1000000;
                    selCity = selValue;
                    selTown = 0;
                } else if(selValue % 100 == 0) {
                    selProv = Math.floor( selValue / 1000000) * 1000000;
                    selCity = Math.floor( selValue / 10000) * 10000;
                    selTown = selValue;
                }else{
					selProv = Math.floor( selValue / 1000000) * 1000000;
                    selCity = Math.floor( selValue / 10000) * 10000;
					selTown = Math.floor( selValue / 100) * 100;
                    selVell = selValue;
				}
            } else {
                selProv = selCity = selTown = selVell = 0;
            }

            //国家
			var html;
			if(step > 4){
				html = "<select name=\"world\" id=\""+conId+"_world\" class=\"text\">\n";
            	html += "<option value='0' >所有国家</option>\n";
				html += "<option value='1' selected='selected'>国内</option>\n";
				html += "<option value='2'>国外</option>\n";
				html += "</select>\n";
			}else{
				html="";
			}
			
			//省
            html += "<select name=\""+name1+"\" id=\""+conId+"_ya_prov\" class=\"text\">\n";
            html += selProv==0 ? "<option value='0'>所有省份</option>\n" :
                                 "<option value='0' selected='selected'>所有省份</option>\n";
            var provs = this.getProvs( selProv );
            for(p in provs) {
                html += provs[p]['sel'] ?  "<option value='"+provs[p]['id']+"' selected='selected'>"+provs[p]['name']+"</option>\n" :
                                           "<option value='"+provs[p]['id']+"'>"+provs[p]['name']+"</option>\n";
                if(provs[p]['sel']){
                    $("#"+conId+"-field").val(provs[p]['trueId']);
                }
            }
            if(selProv == 0 && step > 4){
                $("#"+conId+"-field").val(0);
            }else if(selProv == 0 && step <= 4){
                $("#"+conId+"-field").val(INSIDEID);
            }
            html += "</select>\n";

            //城市
            if( step > 1 ) {
                html += "<select name=\""+name2+"\" id=\""+conId+"_ya_city\" class=\"text\">\n";
                html += selCity==0 ? "<option value='0'>所有城市</option>\n" :
                                     "<option value='0' selected='selected'>所有城市</option>\n";
                if( selProv > 0 ) {
                    var citys = Area.getCitys( selProv, selCity );
                    for(p in citys) {
                        html += citys[p]['sel'] ?  "<option value='"+citys[p]['id']+"' selected='selected'>"+citys[p]['name']+"</option>\n" :
                                                    "<option value='"+citys[p]['id']+"'>"+citys[p]['name']+"</option>\n";
                        if(citys[p]['sel']){
                            $("#"+conId+"-field").val(citys[p]['trueId']);
                        }
                    }
                }
                html += "</select>\n";
            }

            //县区
            var towns = Area.getTowns( selCity, selTown );
            if( step > 2 ) {
                html += "<select name=\""+name3+"\" class=\"text\" id=\""+conId+"_ya_town\">\n";
                html += selTown==0 ? "<option value='0'>所有县区</option>\n" :
                                      "<option value='0' selected='selected'>所有县区</option>\n";
                if( selCity > 0 ) {
                    for(p in towns) {
                        html += towns[p]['sel'] ?  "<option value='"+towns[p]['id']+"' selected='selected'>"+towns[p]['name']+"</option>\n" :
                                                   "<option value='"+towns[p]['id']+"'>"+towns[p]['name']+"</option>\n";
                        if(towns[p]['sel']){
                            $("#"+conId+"-field").val(towns[p]['trueId']);
                        }
                    }
                }
                html += "</select>\n";
            }
			
			//镇
			var vells = Area.getVells(selTown,selVell);
			if( step > 3 ){
				html += "<select name = \""+name4+"\" class =\"text\" id=\""+conId+"_ya_vell\">\n";
				html += selVell==0 ? "<option value='0'>所有镇</option>\n" :
									 "<option value='0' selected = 'selected'>所有镇</option>\n";
				if(selTown > 0){
					for ( p in vells ){
						html += vells[p]['sel'] ? "<option value='"+vells[p]['id']+"' selected='selected'>"+vells[p]['name']+"</option>\n" : 
												  "<option value='"+vells[p]['id']+"'>"+vells[p]['name']+"</option>\n"
                        if(vells[p]['sel']){
                            $("#"+conId+"-field").val(vells[p]['trueId']);
                        }
					}
				}
				html += "</select>\n";
			}
			
			$("#"+conId).append(html);
			
			if(selValue % 1000000 == 0 && step <= 4){
                if(selValue <= 0){
                    $("#"+conId).children("select:gt(0)").hide();
                }else{
                    $("#"+conId).children("select:gt(1)").hide();
                }
			}else if(selValue % 10000 == 0 && step <= 4){
				$("#"+conId).children("select:gt(2)").hide();
			}else if(selValue % 100 == 0 && step <= 4){
				$("#"+conId).children("select:gt(3)").hide();
			}else if(selValue % 1000000 == 0 && step > 4){
				if(selValue <= 0){
					$("#"+conId+"_world").find("option:selected").removeAttr("selected");
					$("#"+conId).children("select:gt(0)").hide();
				}else{
					$("#"+conId).children("select:gt(2)").hide();
				}
			}else if(selValue % 10000 == 0 && step > 4){
				$("#"+conId).children("select:gt(3)").hide();
			}else if(selValue % 100 == 0 && step > 4){
				$("#"+conId).children("select:gt(4)").hide();
			}

            return ;
        }
		
		//国家改变
		this.remakeCountry = function(cinId,countryVal){
			$("#"+cinId+"_ya_city").hide();
			$("#"+cinId+"_ya_town").hide();
			$("#"+cinId+"_ya_vell").hide();

            switch(countryVal){
                case '0' :
                    $("#"+cinId+"-field").val(0);
                    $("#"+cinId+"_ya_prov").hide();
                    break;
                case '1' :
                    $("#"+cinId+"-field").val(INSIDEID);
                    $("#"+cinId+"_ya_prov").show();
                    break;
                case '2' :
                    $("#"+cinId+"-field").val(OUTSIDEID);
                    $("#"+cinId+"_ya_prov").hide();
                    break;
                default :
                    $("#"+cinId+"-field").val(0);
            }
		}
		
		//省份改变
		this.remakeProv = function(cinId){
            var $prov = $( "#"+cinId+'_ya_prov' );
            if( $prov.length < 1 ) return false;
            var aOption = null;
            var provs = Area.getProvs(0);

            $prov.children("option").remove();
            aOption = $("<option></option>").text("所有省份").attr("value",0);
            aOption.appendTo($prov);

            if( provs ) {
                for(var p in provs) {
                    aOption = $("<option></option>").text(provs[p]['name']).attr("value",provs[p]['id']);
                    aOption.appendTo($prov);
                }
            }
            $("#"+cinId).children("select:gt(1)").hide();
		}
		//重新生成城市选择数据
        this.remakeCity = function( cinId, prov ) {
            var $city = $( "#"+cinId+'_ya_city' );
            if( $city.length < 1 ) return false;
            var aOption = null;
            var citys = Area.getCitys( prov, 0 );
			
			$city.children("option").remove();
			aOption = $("<option></option>").text("所有城市").attr("value",0);
			aOption.appendTo($city);
            $("#"+cinId+"_ya_town").hide();
			
            if( citys ) {
                for(p in citys) {
					aOption = $("<option></option>").text(citys[p]['name']).attr("value",citys[p]['id']);
					aOption.appendTo($city);
                }
				$("#"+cinId+"_ya_city").show();
            }
            
			return true;
        }

        //重新生成县区选择数据
        this.remakeTown = function( cinId, city ) {
            var $town = $( "#"+cinId+'_ya_town' );
            if( $town.length < 1 ) return false;
            var aOption = null;
            var towns = Area.getTowns( city, 0 );
			
			$town.children("option").remove();
			aOption = $("<option></option>").text("所有县区").attr("value",0);
			aOption.appendTo($town);
			$("#"+cinId+"_ya_vell").hide();
			
            if( towns ) {
                for(p in towns) {
					aOption = $("<option></option>").text(towns[p]['name']).attr("value",towns[p]['id']);
					aOption.appendTo($town);
                }
				$("#"+cinId+"_ya_town").show();
            }else{
				$("#"+cinId+"_ya_town").hide();
			}
            return true;
        }
		
        //重新生成 镇 选择数据
		this.remakeVell = function( cinId, town) {
			var $vell = $( "#"+cinId+'_ya_vell' );
			if( $vell.length < 1 ) return false;
			var aOption = null;
			var vells = Area.getVells(town,0);
			
			$vell.children("option").remove();
			aOption = $("<option></option>").text("所有镇").attr("value",0);
			aOption.appendTo($vell);
						
			if( vells ) {
				for( p in vells ){
					aOption = $("<option></option>").text(vells[p]['name']).attr("value",vells[p]['id']);
					aOption.appendTo($vell);
				}
				$("#"+cinId+"_ya_vell").show();
			}else{
				$("#"+cinId+"_ya_vell").hide();
			}
			return true;
		}

        //获取当前省
        this.getCurPre = function(level,preVal,preLevelVal){
            var preData,trueId;
            switch (level){
                case 'prov':
                    preData = Area.getProvs(preVal);
                    break;
                case 'city':
                    preData = Area.getCitys(preLevelVal,preVal);
                    break;
                case 'town':
                    preData = Area.getTowns(preLevelVal,preVal);
                    break;
                default :
                    preData = null;
            }

            for(var p in preData ){
                if(preData[p]['sel']){
                    trueId = preData[p]['trueId'];
                    break;
                }
            }
            return trueId;
        }


		//切换地域
		this.changeArea = function(ID){
            //切换国家
			$("#"+ID+"_world").change(function(){
				var val = $(this).val();
				Area.remakeCountry(ID,val);
				Area.remakeProv(ID);
			});
			//切换省
			$("#"+ID+"_ya_prov").change(function(){
				if($(this).val() == 0){
                    $("#"+ID+"-field").val(INSIDEID);
                    if(step > 4){
                        $("#"+ID).children("select:gt(1)").hide();
                    }else{
                        $("#"+ID).children("select:gt(0)").hide();
                    }
                    return ;
				}
                Area.remakeCity(ID,$(this).val());
                var provData = Area.getProvs($(this).val());
                for(var p in provData ){
                    if(provData[p]['sel']){
                        $("#"+ID+"-field").val(provData[p]['trueId']);
                        break;
                    }
                }
			});
            //切换城市
			$("#"+ID+"_ya_city").change(function(){
                if($(this).val()==0){
                    var curProv = $("#"+ID+"_ya_prov").val(),
                        curProId = Area.getCurPre('prov',curProv);
                    $("#"+ID+"-field").val(curProId);
                    return;
                }

				Area.remakeTown(ID,$(this).val());
                var cityData = Area.getCitys($("#"+ID+"_ya_prov").val(),$(this).val());
                for(var p in cityData ){
                    if(cityData[p]['sel']){
                        $("#"+ID+"-field").val(cityData[p]['trueId']);
                        break;
                    }
                }
			});
			$("#"+ID+"_ya_town").change(function(){
                if($(this).val()==0){
                    var curProv = $("#"+ID+"_ya_prov").val(),
                        curCity = $("#"+ID+"_ya_city").val(),
                        curCityId = Area.getCurPre('city',curCity,curProv);
                    $("#"+ID+"-field").val(curCityId);
                    return;
                }

				Area.remakeVell(ID,$(this).val());
                var townData = Area.getTowns($("#"+ID+"_ya_city").val(),$(this).val());
                for(var p in townData ){
                    if(townData[p]['sel']){
                        $("#"+ID+"-field").val(townData[p]['trueId']);
                        break;
                    }
                }
			});

            $("#"+ID+"_ya_vell").change(function(){
                if($(this).val()==0){
                    var curTown = $("#"+ID+"_ya_town").val(),
                        curCity = $("#"+ID+"_ya_city").val(),
                        curTownId = Area.getCurPre('town',curTown,curCity);
                    $("#"+ID+"-field").val(curTownId);
                    return;
                }
                var vellData = Area.getVells($("#"+ID+"_ya_town").val(),$(this).val());
                for(var p in vellData ){
                    if(vellData[p]['id']==$(this).val()){
                        $("#"+ID+"-field").val(vellData[p]['trueId']);
                        break;
                    }
                }
            });
		}
		
	};//类Area end
	module.exports = Area;
});